import requests


class EmbyMediaUtils:
    """媒体库信息获取工具类，支持递归获取文件夹内容（不含播放链接）"""

    def __init__(self, server_url, server_port, api_key, user_id):
        """初始化媒体库工具类"""
        self.server_url = server_url
        self.server_port = server_port
        self.api_key = api_key
        self.user_id = user_id
        self.base_url = f"http://{server_url}:{server_port}"
        self.headers = {
            "Accept": "application/json",
            "X-Emby-Token": api_key
        }

    def get_media_libraries(self):
        """获取媒体服务器上的媒体库信息，包含封面图链接"""
        try:
            media_url = f"{self.base_url}/Users/{self.user_id}/Items"
            response = requests.get(media_url, headers=self.headers)
            response.raise_for_status()
            data = response.json()

            total_count = data.get('TotalRecordCount', 0)
            libraries = []
            for item in data.get('Items', []):
                cover_image = f"{self.base_url}/Items/{item.get('Id')}/Images/Primary" if item.get('Id') else None

                library_info = {
                    'name': item.get('Name', '未知'),
                    'id': item.get('Guid', '未知'),
                    'item_id': item.get('Id', '未知'),
                    'type': item.get('Type', '未知'),
                    'collection_type': item.get('CollectionType', '未知'),
                    'cover_image': cover_image
                }
                libraries.append(library_info)

            return {
                'total_count': total_count,
                'libraries': libraries
            }

        except requests.exceptions.RequestException as e:
            print(f"请求发生错误: {e}")
        return None

    def get_library_resources(self, parent_id, recursive=True):
        """
        获取指定媒体库内的资源，支持递归获取文件夹内容
        仅包含封面图链接（不含播放链接）
        """
        try:
            media_url = f"{self.base_url}/Users/{self.user_id}/Items"
            params = {"parentId": parent_id}

            response = requests.get(media_url, headers=self.headers, params=params)
            response.raise_for_status()
            data = response.json()

            total_count = data.get('TotalRecordCount', 0)
            resources = []
            for item in data.get('Items', []):
                cover_image = f"{self.base_url}/Items/{item.get('Id')}/Images/Primary" if item.get('Id') else None

                resource_info = {
                    'name': item.get('Name', '未知'),
                    'id': item.get('Id', '未知'),
                    'type': item.get('Type', '未知'),
                    'cover_image': cover_image
                }

                if 'RunTimeTicks' in item:
                    resource_info['run_time_ticks'] = item['RunTimeTicks']

                if recursive and resource_info['type'] == 'Folder':
                    sub_resources = self.get_library_resources(resource_info['id'], recursive)
                    resource_info['sub_resources'] = sub_resources['resources']
                    resource_info['sub_total_count'] = sub_resources['total_count']

                resources.append(resource_info)

            return {
                'total_count': total_count,
                'resources': resources
            }

        except requests.exceptions.RequestException as e:
            print(f"请求发生错误: {e}")
        return None